const Layer = require("./layer");
const methods = require("methods");
function Route() {
  this.stack = []; // 用来存放里层的layer
  this.methods = {}; // 用来统计用户的方法 有哪些，为了加速匹配
}
Route.prototype.dispatch = function (req, res, out) {
  let idx = 0;
  let next = (err) => {
    if (err) return out(err);
    if (idx >= this.stack.length) return out(); // 递归的终止条件
    let layer = this.stack[idx++];
    console.log("请求到来，做匹配");
    if (layer.method === req.method.toLowerCase()) {
      // 用户写的逻辑
      layer.handle_request(req, res, next);
    } else {
      next();
    }
  };
  next();
};
methods.forEach((method) => {
  Route.prototype[method] = function (handlers) {
    handlers.forEach((handler) => {
      const layer = new Layer("/XXXXXX", handler); // 里层的layer
      layer.method = method;
      this.methods[layer.method] = true;
      this.stack.push(layer);
    });
  };
});
module.exports = Route;
